<template>
  <view class="container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-content">
        <view class="navbar-left" @click="goBack">
          <text class="back-icon">←</text>
        </view>
        <view class="navbar-title">好友申请</view>
        <view class="navbar-right"></view>
      </view>
    </view>

    <!-- 好友申请列表 -->
    <view class="request-list" v-if="friendRequests.length > 0">
      <view
        v-for="request in friendRequests"
        :key="request.id"
        class="request-item"
      >
        <view class="user-avatar">
          <text class="avatar-text">{{ getAvatarLetterFromUser(request.fromUser) }}</text>
        </view>
        <view class="request-info">
          <view class="user-name">{{ getUserDisplay(request.fromUser) }}</view>
          <view class="request-message">{{ request.message || '请求添加您为好友' }}</view>
          <view class="request-time">{{ formatTime(request.createTime) }}</view>
        </view>
        <view class="action-buttons" v-if="request.status === 'PENDING'">
          <button @click="handleRequest(request, 'REJECTED')" class="reject-btn">拒绝</button>
          <button @click="handleRequest(request, 'ACCEPTED')" class="accept-btn">同意</button>
        </view>
        <view class="status-text" v-else>
          <text :class="getStatusClass(request.status)">{{ getStatusText(request.status) }}</text>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-else-if="!loading">
      <text class="empty-icon">📭</text>
      <text class="empty-text">暂无好友申请</text>
    </view>

    <!-- 加载状态 -->
    <view class="loading" v-if="loading">
      <text>加载中...</text>
    </view>
  </view>
</template>

<script>
import { getReceivedFriendRequests, handleFriendRequest } from "@/utils/api.js";

export default {
  data() {
    return {
      friendRequests: [],
      loading: false,
    };
  },
  onLoad() {
    this.loadFriendRequests();
  },
  onShow() {
    // 页面显示时刷新数据
    this.loadFriendRequests();
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },

    async loadFriendRequests() {
      this.loading = true;
      try {
        const userInfo = uni.getStorageSync("userInfo");
        if (!userInfo) {
          uni.showToast({
            title: "请先登录",
            icon: "none",
          });
          return;
        }

        const result = await getReceivedFriendRequests();
        console.log("好友申请列表:", result);

        if (result.code === 200) {
          this.friendRequests = result.data || [];
        } else {
          uni.showToast({
            title: result.message || "加载失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("加载好友申请失败:", error);
        uni.showToast({
          title: "网络错误，请重试",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },

    async handleRequest(request, action) {
      try {
        const userInfo = uni.getStorageSync("userInfo");
        if (!userInfo) {
          uni.showToast({
            title: "请先登录",
            icon: "none",
          });
          return;
        }

        // 将显示状态转换为接口需要的动作
        const actionMap = { ACCEPTED: 'accept', REJECTED: 'reject' }
        const apiAction = actionMap[action] || action

        const result = await handleFriendRequest(request.id, apiAction);

        console.log("处理好友申请结果:", result);

        if (result.code === 200) {
          // 更新本地状态（保持大写状态码用于显示）
          request.status = action;
          this.$forceUpdate();

          uni.showToast({
            title: action === 'ACCEPTED' ? "已同意好友申请" : "已拒绝好友申请",
            icon: "success",
          });

          // 如果同意了好友申请，可以触发好友列表更新
          if (action === 'ACCEPTED') {
            uni.$emit('friendListUpdate');
          }
        } else {
          uni.showToast({
            title: result.message || "操作失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("处理好友申请失败:", error);
        uni.showToast({
          title: "网络错误，请重试",
          icon: "none",
        });
      }
    },

    // 安全获取用户名
    getUserDisplay(user) {
      if (!user) return '未知用户'
      return user.nickname || user.username || '未知用户'
    },

    // 获取头像首字母（容错）
    getAvatarLetterFromUser(user) {
      const name = this.getUserDisplay(user)
      return name ? name.charAt(0) : '?'
    },

    formatTime(timeString) {
      if (!timeString) return '';
      
      const time = new Date(timeString);
      const now = new Date();
      const diff = now - time;
      
      if (diff < 60000) { // 1分钟内
        return '刚刚';
      } else if (diff < 3600000) { // 1小时内
        return Math.floor(diff / 60000) + '分钟前';
      } else if (diff < 86400000) { // 24小时内
        return Math.floor(diff / 3600000) + '小时前';
      } else {
        return time.toLocaleDateString();
      }
    },

    getStatusText(status) {
      switch (status) {
        case 'ACCEPTED':
          return '已同意';
        case 'REJECTED':
          return '已拒绝';
        case 'PENDING':
          return '待处理';
        default:
          return '未知状态';
      }
    },

    getStatusClass(status) {
      switch (status) {
        case 'ACCEPTED':
          return 'status-accepted';
        case 'REJECTED':
          return 'status-rejected';
        default:
          return 'status-pending';
      }
    },
  },
};
</script>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 自定义导航栏 */
.custom-navbar {
  background-color: #fff;
  padding-top: var(--status-bar-height, 44px);
  border-bottom: 1px solid #e5e5e5;
}

.navbar-content {
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
}

.navbar-left {
  width: 60px;
  display: flex;
  align-items: center;
}

.back-icon {
  font-size: 20px;
  color: #333;
}

.navbar-title {
  font-size: 17px;
  font-weight: 600;
  color: #333;
}

.navbar-right {
  width: 60px;
}

/* 好友申请列表 */
.request-list {
  background-color: #fff;
}

.request-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 25px;
  background-color: #007aff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.avatar-text {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.request-info {
  flex: 1;
}

.user-name {
  font-size: 16px;
  color: #333;
  margin-bottom: 5px;
}

.request-message {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.request-time {
  font-size: 12px;
  color: #999;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.reject-btn, .accept-btn {
  height: 32px;
  padding: 0 15px;
  border: none;
  border-radius: 16px;
  font-size: 14px;
}

.reject-btn {
  background-color: #f5f5f5;
  color: #666;
}

.accept-btn {
  background-color: #007aff;
  color: white;
}

.status-text {
  padding: 0 15px;
}

.status-accepted {
  color: #4cd964;
}

.status-rejected {
  color: #ff3b30;
}

.status-pending {
  color: #ff9500;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 100px 20px;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 20px;
  display: block;
}

.empty-text {
  color: #666;
  font-size: 16px;
}

/* 加载状态 */
.loading {
  text-align: center;
  padding: 50px 20px;
  color: #666;
}
</style>
